package com.legal.aid.app.service.impl;

import com.legal.aid.app.domain.vo.LawRegulationVo;
import com.legal.aid.app.mapper.AppLawRegulationMapper;
import com.legal.aid.app.mapper.AppCollectMapper;
import com.legal.aid.app.service.IAppLawRegulationService;
import com.legal.aid.common.constant.CollectType;
import com.legal.aid.common.core.domain.model.AppLoginUser;
import com.legal.aid.common.core.domain.entity.CommonUser;
import com.legal.aid.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;


@Service
public class AppLawRegulationServiceImpl implements IAppLawRegulationService {

    @Autowired
    private AppLawRegulationMapper appLawRegulationMapper;

    @Autowired
    private AppCollectMapper appCollectMapper;

    @Override
    public List<LawRegulationVo> selectLawRegulationVoList(LawRegulationVo lawRegulation) {
        List<LawRegulationVo> list = appLawRegulationMapper.selectLawRegulationVoList(lawRegulation);
        return Optional.ofNullable(list)
                .filter(l -> !l.isEmpty())
                .orElse(Collections.emptyList());
    }

    @Override
    public LawRegulationVo selectLawRegulationVoByLawId(Long lawId) {
        if(lawId == null ) return null;
        return appLawRegulationMapper.selectLawRegulationVoByLawId(lawId);
    }

    @Override
    public List<LawRegulationVo> selectAttentionLawRegulationVoList() {
        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        System.out.println("当前登录用户： " + (appLoginUser != null ? appLoginUser.getUsername() : "未登录") + ", ID: " + (appLoginUser != null ? appLoginUser.getUserId() : "N/A"));
        CommonUser user = appLoginUser.getCommonUser();
        if(user == null) {
            return Collections.emptyList();
        }
        
        // 将 CollectType.COLLECT_TYPE_LAW_REGULATION 转换为字符串
        String targetType = String.valueOf(CollectType.COLLECT_TYPE_LAW_REGULATION);
        List<Long> targetIds = appCollectMapper.getTargetIdList(targetType, user.getId());
        if(targetIds == null || targetIds.isEmpty()) {
            return Collections.emptyList();
        }
        //根据targetId 查询关注法律法规
        List<LawRegulationVo> list = appLawRegulationMapper.selectLawRegulationVoListByIds(targetIds);
        return Optional.ofNullable(list)
                .filter(l -> !l.isEmpty())
                .orElse(Collections.emptyList());
    }
}
